const axios = require('axios');

async function testAuthFlow() {
  try {
    console.log('测试完整认证流程...\n');

    // 1. 登录获取token
    console.log('1. 登录获取token...');
    const loginResponse = await axios.post('http://localhost:7002/api/v1/user/login', {
      username: 'demo',
      password: '123456'
    });

    if (loginResponse.data.code !== 200) {
      console.log('❌ 登录失败:', loginResponse.data);
      return;
    }

    const token = loginResponse.data.data.token;
    const user = loginResponse.data.data.user;
    console.log('✅ 登录成功');
    console.log('Token:', token.substring(0, 50) + '...');
    console.log('用户信息:', user);

    // 2. 解析token内容
    console.log('\n2. 解析token内容...');
    const tokenParts = token.split('.');
    if (tokenParts.length === 3) {
      try {
        const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64').toString());
        console.log('Token payload:', payload);
      } catch (e) {
        console.log('❌ Token解析失败:', e.message);
      }
    }

    // 3. 测试需要认证的接口
    console.log('\n3. 测试需要认证的接口...');
    const authHeaders = {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    };

    // 测试用户信息接口
    try {
      const profileResponse = await axios.get('http://localhost:7002/api/v1/user/profile', {
        headers: authHeaders
      });
      console.log('✅ 用户信息接口成功:', profileResponse.data);
    } catch (error) {
      console.log('❌ 用户信息接口失败:');
      if (error.response) {
        console.log('状态码:', error.response.status);
        console.log('错误信息:', error.response.data);
      } else {
        console.log('网络错误:', error.message);
      }
    }

    // 测试分析接口
    try {
      const analysisResponse = await axios.get('http://localhost:7002/api/v1/analysis/outfit-style', {
        headers: authHeaders
      });
      console.log('✅ 分析接口成功:', analysisResponse.data);
    } catch (error) {
      console.log('❌ 分析接口失败:');
      if (error.response) {
        console.log('状态码:', error.response.status);
        console.log('错误信息:', error.response.data);
      } else {
        console.log('网络错误:', error.message);
      }
    }

    console.log('\n=== 测试完成 ===');

  } catch (error) {
    console.error('❌ 测试过程中发生错误:', error.message);
  }
}

testAuthFlow();
